﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Runda.CMS.Common.Entity;
using Runda.CMS.Dal;
using Runda.CMS.Common.Utility;
using System.Transactions;
using System.Data;

namespace Runda.CMS.Bll
{
    public class ContractBll:BllBase
    {
        #region Contract 
        /// <summary>
        /// 获取领导要备注的任务
        /// </summary>
        /// <returns></returns>
        public List<WflTaskEntity> GetMyTask(Guid UserID, List<SqlDbParameter> parameters, string OrderBy, int PageSize, int PageIndex, out int RecordCount)
        {
            WflTaskDal dal = new WflTaskDal();
            return dal.GetMyTask(UserID, parameters, OrderBy, PageSize, PageIndex, out RecordCount);
        }

        /// <summary>
        /// 复制一份新合同
        /// </summary>
        /// <param name="ContractID"></param>
        /// <returns></returns>
        public Guid CopyContract(Guid ContractID,string ChangeRemark)
        {
            if (ContractID == Guid.Empty) return Guid.Empty;

            Guid NewContractID = Guid.Empty;
            using (TransactionScope tran = new TransactionScope())
            {
                CtrtContractEntity entity = base.Get<CtrtContractEntity>(ContractID);
                if (entity != null)
                {
                    NewContractID = Guid.NewGuid();

                    //合同基本信息
                    entity.ContractID = NewContractID;
                    entity.CreatedOn = DateTime.Now;
                    entity.InstanceID = Guid.Empty;
                    entity.Status = (int)Enumerator.ContractStatus.Draft;
                    entity.NextCheckers = string.Empty; 
                    entity.OriginalContractID = ContractID;
                    entity.ChangeRemark = ChangeRemark;
                    base.Insert(entity);

                    //合同其他收入明细
                    CtrtContractOthorIncomeExtendEntity othorIncome = base.Get<CtrtContractOthorIncomeExtendEntity>(ContractID);
                    if (othorIncome != null)
                    {
                        othorIncome.ContractID = NewContractID;
                        othorIncome.LastModifiedAt = othorIncome.CreatedAt = DateTime.Now;
                        //othorIncome.LastModifiedBy = othorIncome.CreatedBy = 
                        base.Insert(othorIncome);
                    }

                    //合同明细
                    List<CtrtContractItemEntity> ItemList = base.GetAll<CtrtContractItemEntity>(" and ContractID = '" + ContractID + "'");
                    if (ItemList != null)
                    {
                        foreach (CtrtContractItemEntity item in ItemList)
                        {
                            item.ItemID = Guid.NewGuid();
                            item.ContractID = NewContractID;
                            base.Insert(item);
                        }
                    }
                    //合同文档
                    List<CtrtDocumentEntity> DocumentList = base.GetAll<CtrtDocumentEntity>(" and ContractID = '" + ContractID + "'");
                    if (DocumentList != null)
                    {
                        foreach (CtrtDocumentEntity document in DocumentList)
                        {
                            document.DocumentID = Guid.NewGuid();
                            document.ContractID = NewContractID;
                            base.Insert(document);
                        }
                    }

                    //合同配套商品
                    List<CtrtContractGiftEntity> GiftList = base.GetAll<CtrtContractGiftEntity>(" and ContractID = '"+ContractID+"'");
                    if (GiftList != null)
                    {
                        foreach (CtrtContractGiftEntity gift in GiftList)
                        {
                            gift.GiftID = Guid.NewGuid();
                            gift.ContractID = ContractID;
                            base.Insert(gift);
                        }
                    }

                    //合同支付方式
                    List<CtrtContractPaymentEntity> PaymentList = base.GetAll<CtrtContractPaymentEntity>(" and ContractID = '"+ContractID+"'");
                    if (PaymentList != null)
                    {
                        foreach (CtrtContractPaymentEntity payment in PaymentList)
                        {
                            payment.PaymentID = Guid.NewGuid();
                            payment.ContractID = NewContractID;
                            payment.CreatedAt = DateTime.Now;
                            base.Insert(payment);
                        }
                    }

                }

                tran.Complete();
            }

            return NewContractID;
        }

    
        public DataTable QueryContract(string whereClause, string OrderBy, int PageSize, int PageIndex, out int RecordCount)
        {
            CtrtContractDal dal = new CtrtContractDal();
            return dal.QueryContract(whereClause, OrderBy, PageSize, PageIndex, out RecordCount);
        }

        /// <summary>
        /// 投放合同利润率
        /// </summary>
        /// <param name="ContractID"></param>
        /// <returns></returns>
        public void CalculateContractProfitRate(Guid ContractID)
        {
            CtrtContractEntity contract = this.Get<CtrtContractEntity>(ContractID);
            List<CtrtContractItemEntity> items = GetAll<CtrtContractItemEntity>(" and ParentID is not null and ContractID = '"+ContractID+"'");

            decimal ProfitRate = 0;
            decimal i = 0;
            foreach (CtrtContractItemEntity entity in items)
            { 
                if(!entity.IsCalcProfit)continue; 
                if (entity.Price == 0) continue;
                ProfitRate += (entity.Price * contract.PutDiscount - entity.Cost) / (entity.Price * contract.PutDiscount);
                i++;
            }

            if (i == 0)
            { ProfitRate = 0; }
            else
            {
                ProfitRate = ProfitRate / i;
            }

            CtrtContractEntity contractentity = this.Get<CtrtContractEntity>(ContractID);
            contractentity.ContractProfitRate = ProfitRate;
            this.Update(contractentity);
        }

        /// <summary>
        /// 检查合同编号是否重复
        /// 主要逻辑:新增状态下查询所有记录是否存在
        ///              修改状态下除去自己和有与该合同相关联的合同是否存在
        /// </summary>
        /// <param name="ContractID"></param>
        /// <param name="ContractCode"></param>
        /// <returns></returns>
        public OperateResult CheckContractCode(Guid ContractID,string ContractCode)
        {
            OperateResult result = new OperateResult();
            result.Result = true;

            CtrtContractEntity entity = null;
            if (ContractID == Guid.Empty) //新增
            {
                entity = this.Get<CtrtContractEntity>(" and ContractCode = '" + ContractCode + "' and Deleted=0");
                if (entity != null)
                {
                    result.ErrorMessage = "合同编号已存在!";
                    result.Result = false;
                }
            }
            else //修改
            { 

                CtrtContractDal dal = new CtrtContractDal();
                List<CtrtContractEntity> Groups = dal.GetContractNotInGroup(ContractID,ContractCode);
                if (Groups != null && Groups.Count >0)
                {
                    result.ErrorMessage = "合同编号已存在!";
                    result.Result = false;
                }
            }

            return result;
        }

        /// <summary>
        /// 终止或者驳回合同
        /// </summary>
        /// <param name="ContractID"></param>
        /// <param name="CommandName"></param>
        public void CommitContract(Guid ContractID,Guid UserID,string UserName, string CommandName)
        {
            CtrtContractEntity entity = null;
            entity = this.Get<CtrtContractEntity>(ContractID);
            if (entity == null) return;

            using (System.Transactions.TransactionScope tran = new TransactionScope())
            {
                if (CommandName == "abort")
                {
                    entity.Status = (int)Enumerator.ContractStatus.Abort;
                    entity.LastModifiedAt = DateTime.Now;
                    entity.LastModifiedBy = UserID;
                    this.Update(entity);

                    WflInstanceRoutingEntity trackEntity = new WflInstanceRoutingEntity();
                    trackEntity.InstanceID = entity.InstanceID;
                    trackEntity.CheckBy = UserID;
                    trackEntity.CheckName = UserName;
                    trackEntity.CheckStatus = 3;//(byte)ActivityStatus.Reject;
                    trackEntity.Comment = "终止合同";
                    trackEntity.CheckDate = DateTime.Now;
                    trackEntity.Deleted = false;
                    this.Insert(trackEntity);
                }
                else if (CommandName == "rebut")
                {
                    entity.Status = (int)Enumerator.ContractStatus.Draft;
                    entity.LastModifiedAt = DateTime.Now;
                    entity.LastModifiedBy = UserID;
                    this.Update(entity);

                    WflInstanceRoutingEntity trackEntity = new WflInstanceRoutingEntity();
                    trackEntity.InstanceID = entity.InstanceID;
                    trackEntity.CheckBy = UserID;
                    trackEntity.CheckName = UserName;
                    trackEntity.CheckStatus = 3;//(byte)ActivityStatus.Reject;
                    trackEntity.Comment = " 驳回合同";
                    trackEntity.CheckDate = DateTime.Now;
                    trackEntity.Deleted = false;
                    this.Insert(trackEntity);
                }

                tran.Complete();
            }
        }
        #endregion

        #region Instrument
        public List<CtrtInstrumentEntity> GetInstrumentEntities(Guid CategoryID)
        {
            CtrtInstrumentDal dal = new CtrtInstrumentDal();
            return dal.GetInstrumentEntities(CategoryID);
        }

        public DataTable GetInstrumentEntities(Guid CategoryID,string CustomerCode)
        {
            CtrtInstrumentDal dal = new CtrtInstrumentDal();
            return dal.GetInstrumentEntities(CategoryID, CustomerCode);
        }


        public List<CtrtInstrumentEntity> GetInstrumentEntities(string Code)
        {
            CtrtInstrumentDal dal = new CtrtInstrumentDal();
            return dal.GetInstrumentEntities(Code);
        }

        public DataTable GetInstrumentEntities(string Code, string CustomerCode)
        {
            CtrtInstrumentDal dal = new CtrtInstrumentDal();
            return dal.GetInstrumentEntities(Code, CustomerCode);
        }
        //判断存货树的节点是否叶子
        public int TreeNodeIsLeaf(string categoryName)
        {
            return System.Convert.ToInt16(new CommonBll().getDataFromSQL("select COUNT(*) from Cms_Ctrt_InstrumentCategory where isLastLevel = 1 and categoryGUID = '"+categoryName+"'").Rows[0][0]);
        }
        #endregion

        #region contract item

        public void InsertOrUpdateContractItems(List<CtrtContractItemEntity> items)
        {
            if (items == null || items.Count ==0) return;
            CtrtContractItemDal dal = new CtrtContractItemDal();
 
            foreach (CtrtContractItemEntity item in items)
            {
                CtrtContractItemEntity entity = null;
                if (item.ParentID == Guid.Empty)
                {
                    entity = dal.Get<CtrtContractItemEntity>(" and ContractID = '" + item.ContractID.ToString() + "' and instrumentGUID = '" + item.instrumentGUID.ToString() + "'");
                }
                else
                {
                    entity = dal.Get<CtrtContractItemEntity>(" and ContractID = '" + item.ContractID.ToString() + "' and instrumentGUID = '" + item.instrumentGUID.ToString() + "' and ParentID = '"+item.ParentID.ToString()+"'");                
                }

                if (entity != null) continue;

                CtrtInstrumentEntity instrument = Get<CtrtInstrumentEntity>(item.instrumentGUID);
                item.CategoryCode = instrument.CategoryCode;
                item.ItemStandard = instrument.instrumentStandard;
                item.Unit = instrument.unit;
                item.IsCalcProfit = true;
                dal.Insert(item);
            }
            CalculateContractProfitRate(items[0].ContractID);
        }

        public DataTable GetContractItemTable(string WhereClause, string OrderBy)
        {
            CtrtContractItemDal dal = new CtrtContractItemDal();
            return dal.GetContractItemTable(WhereClause, OrderBy);
        }

        public void DeleteContractItem(Guid ItemID)
        {
            using (System.Transactions.TransactionScope tran = new TransactionScope())
            {   
                List<SqlDbParameter> Parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "ItemID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@ItemID";
                parm.ParameterValue = ItemID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                Parms.Add(parm);
                 
                this.Delete<CtrtItemGuarantyEntity>(Parms);

 
                Parms.Clear();
                parm = new SqlDbParameter();
                parm.ColumnName = "ParentID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@ParentID";
                parm.ParameterValue = ItemID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                Parms.Add(parm);

                this.Delete<CtrtContractItemEntity>(Parms);

                this.Delete(new CtrtContractItemEntity(ItemID));           

                tran.Complete();
            }
        }

        /// <summary>
        /// 保存配套试剂
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="items"></param>
        public void SaveContractSubItem(CtrtContractEntity entity, List<CtrtContractItemEntity> items)
        {
            using (System.Transactions.TransactionScope tran = new TransactionScope())
            {
                this.Update(entity);

                foreach (CtrtContractItemEntity item in items)
                {
                    this.Update(item);
                }
                tran.Complete();
            }
        }

   　  /// <summary>
   　  /// 重新计算配套试剂价格
    　 /// </summary>
   　  /// <param name="entity"></param>
    　 /// <param name="items"></param>
        public void CalculateContractSubItem(CtrtContractEntity entity, List<CtrtContractItemEntity> items)
        {
            using (System.Transactions.TransactionScope tran = new TransactionScope())
            {
                foreach (CtrtContractItemEntity item in items)
                {
                    item.TotalPrice = item.Count * item.Price * entity.PutDiscount;
                    this.Update(item);
                }
                tran.Complete();
            }
        }
        #endregion

        #region Contract Payment
        /// <summary>
        /// 组织付款项
        /// </summary>
        /// <param name="ContractID">合同ID</param>
        /// <param name="Period">期数</param>
        /// <returns>是否新加过记录</returns>
        public bool BuildContractPayment(Guid ContractID, int Period)
        {
            int CurrCount = this.Count<CtrtContractPaymentEntity>(" and ContractID = '" + ContractID + "'");

            if (CurrCount != 0)
            {
                if (CurrCount >= Period) 
                    return false;
            }
            CtrtContractPaymentEntity entity = null;
            for (int i = CurrCount; i < Period; i++)
            {
                entity = new CtrtContractPaymentEntity();
                entity.ContractID = ContractID;
                this.Insert(entity);
            }
            return true;
        }

        /// <summary>
        /// 保存合同付款信息
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="ContractPayList"></param>
        public void SaveContractPayment(CtrtContractEntity entity, List<CtrtContractPaymentEntity> ContractPayList)
        {
            using (System.Transactions.TransactionScope tran = new TransactionScope())
            {
                this.Update(entity);

                if (ContractPayList != null)
                {
                    foreach (CtrtContractPaymentEntity PayEntity in ContractPayList)
                    {
                        this.Update(PayEntity);
                    }
                }
                tran.Complete();
            }
        }
        #endregion

        #region Contract Gift

        public void SelectGift(List<CtrtContractGiftEntity> list)
        {
            if (list == null) return;

            string WhereClauseFormate = " and ContractID = '{0}' and InstrumentID = '{1}'";
            foreach (CtrtContractGiftEntity entity in list)
            {
                if (this.Count<CtrtContractGiftEntity>(string.Format(WhereClauseFormate,entity.ContractID.ToString(),entity.InstrumentID.ToString())) == 0)
                {
                    this.Insert(entity);
                }
            }
        }

        public DataTable LoadContractGift(Guid ContractID)
        {
            CtrtContractGiftDal dal = new CtrtContractGiftDal();
            return dal.LoadGiftByContractID(ContractID);
        }
        #endregion
        
        #region Contract Item Part

        public void InsertOrUpdateContractItemPart(List<CtrtContractItemPartEntity> items)
        {
            if (items == null) return;
            CtrtContractItemPartDal dal = new CtrtContractItemPartDal();

            foreach (CtrtContractItemPartEntity item in items)
            {
                CtrtContractItemEntity entity = null;
              
                    entity = dal.Get<CtrtContractItemEntity>(" and ContractID = '" + item.ItemID.ToString() + "' and instrumentGUID = '" + item.InstrumentID.ToString() + "'");
              
                if (entity != null) continue;

                //CtrtInstrumentEntity instrument = Get<CtrtInstrumentEntity>(item.InstrumentID);
                //item.CategoryCode = instrument.CategoryCode;
                //item.ItemStandard = instrument.instrumentStandard;
                //item.Unit = instrument.unit;
                dal.Insert(item);
            }
        }

        /// <summary>
        /// 获取合同明细项
        /// </summary>
        /// <param name="ItemID"></param>
        /// <returns></returns>
        public DataTable GetContractItemPart(Guid ItemID)
        {
            CtrtContractItemPartDal dal = new CtrtContractItemPartDal();
            return dal.GetContractItemPart(ItemID);
        }
        #endregion

        #region Contract Report
        public DataSet GetContractTrack(List<Guid> customers,List<string> Years)
        {
            RptPutTrackStatisticsDal dal = new RptPutTrackStatisticsDal();
            string WhereClause = " and A.CustomerID in ({0}) and A.TrackYear in ({1})";

            StringBuilder sbCustomer = new StringBuilder();
            StringBuilder sbYear = new StringBuilder();

            foreach (Guid c in customers)
            {
                if (sbCustomer.Length != 0)
                {
                    sbCustomer.Append(",");
                }
                sbCustomer.Append("'").Append(c).Append("'");
            }
            foreach (string year in Years)
            {
                if (sbYear.Length != 0)
                {
                    sbYear.Append(",");
                }
                sbYear.Append("'").Append(year).Append("'");
            }

            WhereClause = string.Format(WhereClause, sbCustomer.ToString(), sbYear.ToString());

            return dal.GetContractTrack(WhereClause);
        }
        #endregion

        #region Contract Customer
        public DataTable GetCustomerTableByUserID(Guid UserID)
        {
            CtrtCustomerDal dal = new CtrtCustomerDal();
            return dal.GetCustomerTableByUserID(UserID);
        }
        #endregion


    }
}
